"""""""""""""""""vundle""""""""""""""""""""""""""""""""""""""
set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'

Plugin 'Valloric/YouCompleteMe'

Plugin 'scrooloose/syntastic'
" The following are examples of different formats supported.
" Keep Plugin commands between vundle#begin/end.
" plugin on GitHub repo
""Plugin 'tpope/vim-fugitive'
" plugin from http://vim-scripts.org/vim/scripts.html
" Plugin 'L9'
" Git plugin not hosted on GitHub
""Plugin 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
""Plugin 'file:///home/gmarik/path/to/plugin'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
""Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" Install L9 and avoid a Naming conflict if you've already installed a
" different version somewhere else.
" Plugin 'ascenator/L9', {'name': 'newL9'}

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line

"end""""""""""""""""vundle""""""""""""""""""""""""""""""""""""""


"""""YouComPleteMe""""""""""""""""""
let g:ycm_error_symbol = '>>'  
let g:ycm_warning_symbol = '>*'  
let g:ycm_global_ycm_extra_conf='~/new_vim/bundle/YouCompleteMe/.ycm_extra_conf.py'
nmap <F2> :YcmDiags<CR> 
nmap <c-h> :YcmCompleter GoToInclude<CR> 
nmap <c-]> :YcmCompleter GoToDefinitionElseDeclaration<CR>  
""let g:ycm_confirm_extra_conf=0
"""end YouComPleteMe"""""""""""""""

set ts=4   "设置table=4

set number  " 显示行号

set cul "高亮光标所在行
"set cuc "高亮光标所在列

set ruler                   " 打开状态栏标尺

set laststatus=2    " 启动显示状态行(1),总是显示状态行(2)  
set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %{strftime(\"%d/%m/%y\ -\ %H:%M\")}   "状态行显示的内容  

syntax on  "语法高亮

set expandtab     " 不要用空格代替制表符

set ignorecase   "搜索忽略大小写

set iskeyword+=_,$,@,%,#,-		" 带有如下符号的单词不要被换行分割

"""""""根据文件编码来设置编码""""""""""""""""""""""""""""""
set encoding=UTF-8
set langmenu=utf-8
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
"""""""根据文件编码来设置编码""""""""""""""""""""""""""""""

set scrolloff=3     " 光标移动到buffer的顶部和底部时保持3行距离  

:inoremap { {<CR>}<ESC>O
:inoremap } <c-r>=ClosePair('}')<CR>
:inoremap [ []<ESC>i
:inoremap ( ()<ESC>i
:inoremap ) <c-r>=ClosePair(')')<CR>
:inoremap ] <c-r>=ClosePair(']')<CR>
:inoremap " ""<ESC>i
:inoremap ' ''<ESC>i
function! ClosePair(char)
	if getline('.')[col('.') - 1] == a:char
		return "\<Right>"
	else
		return a:char
	endif
endfunction


"""""搜索逐字符高亮"""""""
set hlsearch
set incsearch
"""""搜索逐字符高亮"""""""

set showmatch   "高亮显示匹配的括号

""""""""""""""""""""""""" 跨终端粘贴"""""""""""""""""
let g:copy_file=$HOME . "/.vim_copybuffer"
function Write_copy_file()
    "本函数将 @" 缓冲区内容写入文件
    let lines=split(@", "\n")
    call writefile(lines,g:copy_file)
endfunction
function Read_copy_file()
    "将copy_file文件写入@" 缓冲区，并且粘贴
    let l:buf=readfile(g:copy_file)
    let @"=join(l:buf,"\n")
    normal ""p
endfunction
nmap <silent> ;y :call Write_copy_file()<Enter>
nmap <silent> ;p :call Read_copy_file()<Enter>
""""""""""""""""""""""""" 跨终端粘贴"""""""""""""""""


""""""""""""""""""""""""插入函数注释头"""""""""""""""
func InsertNote()
    call setline(".","/**")
    call append(line("."), " *\\brief")
    call append(line(".")+1, " *")
    call append(line(".")+2, " * \\retval")
    call append(line(".")+3, " *")
    call append(line(".")+4, " * \\created in ".strftime("%F")." by wanglong" )
    call append(line(".")+5, " *")
    call append(line(".")+6, " * \\modified in ".strftime("%F")." by wanglong")
    call append(line(".")+7, " */")
endfunc

map <F4> :call InsertNote() <RETURN> " F4 调用
""""""""""""""""""""""""插入函数注释头""""""""""""""""""""

"""""""""""新建.c,.h,.sh,.java文件，自动插入文件头 """""""""""""""
autocmd BufNewFile *.cpp,*.[ch],*.sh,*.rb,*.java,*.py exec ":call SetTitle()" 
""定义函数SetTitle，自动插入文件头 
func SetTitle() 
    "如果文件类型为.sh文件 
    if &filetype == 'sh' 
        call setline(1,"\#!/bin/bash") 
        call append(line("."), "") 
    elseif &filetype == 'python'
        call setline(1,"#!/usr/bin/env python")
        call append(line("."),"# coding=utf-8")
        call append(line(".")+1, "") 
    elseif &filetype == 'ruby'
        call setline(1,"#!/usr/bin/env ruby")
        call append(line("."),"# encoding: utf-8")
        call append(line(".")+1, "")
        "    elseif &filetype == 'mkd'
        "        call setline(1,"<head><meta charset=\"UTF-8\"></head>")
    else 
        call setline(1, "/*************************************************************************") 
        call append(line("."), "	> File Name: ".expand("%")) 
        call append(line(".")+1, "	> Author: Wang.Long ") 
        call append(line(".")+2, "	> Mail: ") 
        call append(line(".")+3, "	> Created Time: ".strftime("%F")) 
        call append(line(".")+4, " ************************************************************************/") 
        call append(line(".")+5, "")
    endif
    if expand("%:e") == 'cpp'
        call append(line(".")+6, "#include<iostream>")
        call append(line(".")+7, "using namespace std;")
        call append(line(".")+8, "")
    endif


    if &filetype == 'c'
        call append(line(".")+6, "#include <stdio.h>")
        call append(line(".")+7, "#if 0" ) 
        call append(line(".")+8, "#define LOGTRACE           printf(\"========%s========\\n \", __func__)")
        call append(line(".")+9, "#define LOGMSG(fmt, ...)   printf(\"%s line %d MSG: \"fmt, __func__, __LINE__, ##__VA_ARGS__)")
        call append(line(".")+10,"#define LOGERR(fmt, ...)   printf(\"\\033[31m%s line %d ERR: \\033[0m \" fmt, __func__, __LINE__, ##__VA_ARGS__)")
        call append(line(".")+11,"#define DUMP(data, len)    do{UINT _i;CHAR *_p=(CHAR *)data;for(_i=0;_i<len;_i++){if(isprint(_p[_i]))printf(\"%c\",_p[_i]);else printf(\"\\033[31m%02X\\033[0m\",(BYTE)_p[_i]);}printf(\"\\n\");}while(0)")
        call append(line(".")+12,"#else")
        call append(line(".")+13,"#define LOGTRACE")
        call append(line(".")+14,"#define LOGMSG(fmt, ...)")
        call append(line(".")+15,"#define LOGERR(fmt, ...)   printf(\"\\033[31mfunc %s line %d: \\033[0m \" fmt, __func__, __LINE__, ##__VA_ARGS__)")
        call append(line(".")+16,"#define DUMP(data, len)")
        call append(line(".")+17,"#endif")
        call append(line(".")+18,"")

    endif
    if expand("%:e") == 'h'
        call append(line(".")+6, "#ifndef _".toupper(expand("%:r"))."_H")
        call append(line(".")+7, "#define _".toupper(expand("%:r"))."_H")
        call append(line(".")+8, "#endif")
    endif
    if &filetype == 'java'
        call append(line(".")+6,"public class ".expand("%:r"))
        call append(line(".")+7,"")
    endif
    "新建文件后，自动定位到文件末尾
endfunc 
autocmd BufNewFile * normal G
"""""""""""新建.c,.h,.sh,.java文件，自动插入文件头 """""""""""""""

"""""""""""""""""C，C++ 按F5编译运行""""""""""""""""""""
map <F5> :call CompileRunGcc()<CR>
func! CompileRunGcc()
    exec "w"
    if &filetype == 'c'
        exec "!g++ % -o %<"
        exec "!time ./%<"
    elseif &filetype == 'cpp'
        exec "!g++ % -o %<"
        exec "!time ./%<"
    elseif &filetype == 'java' 
        exec "!javac %" 
        exec "!time java %<"
    elseif &filetype == 'sh'
        :!time bash %
    elseif &filetype == 'python'
        exec "!time python2.7 %"
    elseif &filetype == 'html'
        exec "!firefox % &"
    elseif &filetype == 'go'
        "        exec "!go build %<"
        exec "!time go run %"
    elseif &filetype == 'mkd'
        exec "!~/.vim/markdown.pl % > %.html &"
        exec "!firefox %.html &"
    endif
endfunc
"""""""""""""""""C，C++ 按F5编译运行""""""""""""""""""""


map <F3> :NERDTreeToggle<CR>		"列出当前目录文件  

"""""""""""""""C,C++的调试"""""""""""""""
map <F8> :call Rungdb()<CR>
func! Rungdb()
    exec "w"
    exec "!g++ % -g -o %<"
    exec "!gdb ./%<"
endfunc
"end""""""""""""""C,C++的调试"""""""""""""""


"代码格式优化化
map <F6> :call FormartSrc()<CR><CR>
"定义FormartSrc()
func FormartSrc()
    exec "w"
    if &filetype == 'c'
        exec "!astyle --style=ansi -a --suffix=none %"
    elseif &filetype == 'cpp' || &filetype == 'hpp'
        exec "r !astyle --style=ansi --one-line=keep-statements -a --suffix=none %> /dev/null 2>&1"
    elseif &filetype == 'perl'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'py'||&filetype == 'python'
        exec "r !autopep8 -i --aggressive %"
    elseif &filetype == 'java'
        exec "!astyle --style=java --suffix=none %"
    elseif &filetype == 'jsp'
        exec "!astyle --style=gnu --suffix=none %"
    elseif &filetype == 'xml'
        exec "!astyle --style=gnu --suffix=none %"
    else
        exec "normal gg=G"
        return
    endif
    exec "e! %"
endfunc
"结束定义FormartSrc

"当打开vim且没有文件时自动打开NERDTree
autocmd vimenter * if !argc() | NERDTree | endif


"if has("cscope")
"
"    """"""""""""" Standard cscope/vim boilerplate
"
"    " use both cscope and ctag for 'ctrl-]', ':ta', and 'vim -t'
"    set cscopetag
"
"    " check cscope for definition of a symbol before checking ctags: set to 1
"    " if you want the reverse search order.
"    set csto=0
"
"    " add any cscope database in current directory
"    if filereadable("cscope.out")
"     cs add cscope.out  
"
"    else
"
"        let cscope_file=findfile("cscope.out",".;")  
"        let cscope_pre=matchstr(cscope_file,".*/")  
"        if !empty(cscope_file) && filereadable(cscope_file)  
"            exe "cs add" cscope_file cscope_pre  
"        endif      
"    " else add the database pointed to by environment variable 
""      elseif $CSCOPE_DB != ""
""        cs add $CSCOPE_DB
"    endif
"
"    " show msg when any other cscope db added
"    set cscopeverbose  
"
""cscope相关的快捷键映射
"nmap ff <c-]>
"
""s:查找即查找C语言符号出现的地方
"nmap fs :cs find s <C-R>=expand("<cword>")<CR><CR>
"
""g:查找函数、宏、枚举等定义的位置
"nmap fg :cs find g <C-R>=expand("<cword>")<CR><CR>
"
""c:查找光标下的函数被调用的地方
"nmap fc :cs find c <C-R>=expand("<cword>")<CR><CR>
"
""t: 查找指定的字符串出现的地方
"nmap ft :cs find t <C-R>=expand("<cword>")<CR><CR>
"
""e:egrep模式查找,相当于egrep功能
"nmap fe :cs find e <C-R>=expand("<cword>")<CR><CR>
"
""f: 查找文件名,相当于lookupfile
"nmap fn :cs find f <C-R>=expand("<cfile>")<CR><CR>
"
""i: 查找当前文件名出现过的地方
"nmap fi :cs find i <C-R>=expand("<cfile>")<CR><CR>
"
""d: 查找本当前函数调用的函数
"nmap fd :cs find d <C-R>=expand("<cword>")<CR><CR>"))))))))"
"
"endif
"
